package com.qyhl.school.school.column.detail;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolCourseListBean;
import com.qyhl.webtv.commonlib.entity.school.SchoolDetailBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.expandableView.text.ExpandableTextView;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_COLUMN_DETAIL)
public class SchoolColumnDetailActivity extends BaseActivity
        implements SchoolColumnDetailContract.SchoolColumnDetailView {
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.cover)
    RoundedImageView cover;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.cover_layout)
    RelativeLayout coverLayout;
    @BindView(R2.id.summary)
    ExpandableTextView summary;
    @BindView(R2.id.news_layout)
    RelativeLayout newsLayout;
    @BindView(R2.id.news_recycler)
    RecyclerView newsRecycler;
    @BindView(R2.id.live_layout)
    RelativeLayout liveLayout;
    @BindView(R2.id.live_recycler)
    RecyclerView liveRecycler;
    @BindView(R2.id.info_layout)
    RelativeLayout infoLayout;
    @BindView(R2.id.info_recycler)
    RecyclerView infoRecycler;
    @BindView(R2.id.course_layout)
    RelativeLayout courseLayout;
    @BindView(R2.id.course_recycler)
    RecyclerView courseRecycler;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R2.id.motto)
    TextView motto;
    @BindView(R2.id.video_layout)
    CardView videoLayout;

    private SchoolColumnDetailPresenter mPresenter;

    private int schoolId;

    private SchoolDetailBean mBean;

    private CommonAdapter<NewsBean> newsAdapter;
    private List<NewsBean> newsList = new ArrayList<>();

    private CommonAdapter<TeleTextBean> liveAdapter;
    private List<TeleTextBean> liveList = new ArrayList<>();

    private CommonAdapter<NewsBean> infoAdapter;
    private List<NewsBean> infoList = new ArrayList<>();

    private CommonAdapter<SchoolCourseListBean> courseAdapter;
    private List<SchoolCourseListBean> courseList = new ArrayList<>();

    @Override
    protected int getContentView() {
        return R.layout.activity_school_column_detail_new;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarDarkFont(false)
                .titleBar(titleLayout)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new SchoolColumnDetailPresenter(this);
        schoolId = getIntent().getIntExtra("schoolId", 0);


        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        newsRecycler.setLayoutManager(new GridLayoutManager(this, 2));
        newsRecycler.setAdapter(newsAdapter = new CommonAdapter<NewsBean>(this, R.layout.item_school_column_detail_news_list, newsList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean newsBean, int i) {
                viewHolder.setText(R.id.title, newsBean.getTitle());

                viewHolder.setText(R.id.date, DateUtils.mTranslateDate(newsBean.getPublishDate()));

                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolColumnDetailActivity.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);
            }
        });

        liveRecycler.setLayoutManager(new LinearLayoutManager(this));
        liveRecycler.setAdapter(liveAdapter = new CommonAdapter<TeleTextBean>(this, R.layout.item_school_column_detail_live, liveList) {
            @Override
            protected void convert(ViewHolder viewHolder, TeleTextBean teleTextBean, int i) {
                viewHolder.setText(R.id.title, teleTextBean.getTitle());

                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolColumnDetailActivity.this)
                        .load(teleTextBean.getCoverPic())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);
            }
        });

        infoRecycler.setLayoutManager(new LinearLayoutManager(this));
        infoRecycler.setAdapter(infoAdapter = new CommonAdapter<NewsBean>(this, R.layout.item_school_column_detail_info, infoList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean newsBean, int i) {
                viewHolder.setText(R.id.title, newsBean.getTitle());

                viewHolder.setText(R.id.date, DateUtils.mTranslateDate(newsBean.getPublishDate()));

                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolColumnDetailActivity.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

            }
        });

        courseRecycler.setLayoutManager(new LinearLayoutManager(this));
        courseRecycler.setAdapter(courseAdapter = new CommonAdapter<SchoolCourseListBean>(this, R.layout.item_school_column_course, courseList) {
            @Override
            protected void convert(ViewHolder viewHolder, SchoolCourseListBean bean, int i) {
                RoundedImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(SchoolColumnDetailActivity.this)
                        .load(bean.getCover())
                        .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                        .into(cover);

                viewHolder.setText(R.id.title, bean.getTitle());

                viewHolder.setText(R.id.summary, bean.getInfo());
            }
        });

        mPresenter.getDetail(schoolId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(schoolId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDetail(schoolId);
            }
        });

        newsAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                newsSkip(newsList.get(i));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        liveAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.TELE_VIDEO_ACTIVITY)
                        .withString("id", liveList.get(i).getId() + "")
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        courseAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SCHOOL_COLUMN_COURSE_DETAIL)
                        .withInt("albumId",courseList.get(i).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

        infoAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                newsSkip(infoList.get(i));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });


    }

    @Override
    public void setDetail(SchoolDetailBean bean) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        refresh.finishRefresh();

        mBean = bean;

        if (StringUtils.isNotEmpty(bean.getVideoUrl())) {
            videoLayout.setVisibility(View.VISIBLE);
            coverLayout.setVisibility(View.GONE);

            ImageView imageView = new ImageView(this);
            Glide.with(this)
                    .load(mBean.getLogo())
                    .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                    .into(imageView);

            videoPlayer.setThumbImageView(imageView);//设置封面图
            videoPlayer.setRotateViewAuto(false);
            videoPlayer.setLockLand(true);
            videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
            videoPlayer.setShowFullAnimation(false);
            videoPlayer.setUp(mBean.getVideoUrl(), false, "");
            videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {
                    //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusBar
                    videoPlayer.startWindowFullscreen(SchoolColumnDetailActivity.this, true, true);
                }
            });


            videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

        } else {
            videoLayout.setVisibility(View.GONE);
            coverLayout.setVisibility(View.VISIBLE);
        }

        titleName.setText(bean.getName());

        motto.setText(bean.getMotto());

        Glide.with(this)
                .load(bean.getLogo())
                .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                .into(cover);

        summary.setText(bean.getDetail());

        if (bean.getNewsList() != null && bean.getNewsList().size() > 0) {
            newsLayout.setVisibility(View.VISIBLE);

            newsList.clear();
            newsList.addAll(bean.getNewsList());
            newsAdapter.notifyDataSetChanged();
        } else {
            newsLayout.setVisibility(View.GONE);
        }

        if (bean.getLiveList() != null && bean.getLiveList().size() > 0) {
            liveLayout.setVisibility(View.VISIBLE);

            liveList.clear();
            liveList.addAll(bean.getLiveList());
            liveAdapter.notifyDataSetChanged();
        } else {
            liveLayout.setVisibility(View.GONE);
        }

        if (bean.getInfoList() != null && bean.getInfoList().size() > 0) {
            infoLayout.setVisibility(View.VISIBLE);

            infoList.clear();
            infoList.addAll(bean.getInfoList());
            infoAdapter.notifyDataSetChanged();
        } else {
            infoLayout.setVisibility(View.GONE);
        }

        if (bean.getAlbumList() != null && bean.getAlbumList().size() > 0) {
            courseLayout.setVisibility(View.VISIBLE);

            courseList.clear();
            courseList.addAll(bean.getAlbumList());
            courseAdapter.notifyDataSetChanged();
        } else {
            courseLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        refresh.finishRefresh();
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.release();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void newsSkip(NewsBean bean) {
        switch (bean.getType()) {
            case "1"://普通新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
            }
            break;
            case "2"://图片新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("section", bean.getCatalogID());
                RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
            }

            break;
            case "3"://直播
            {
                Bundle bundle = new Bundle();
                bundle.putString("newsId", bean.getID());
                bundle.putString("liveType", bean.getLivetype());
                RouterManager.router(ARouterPathConstant.LIVE_NORMAL_ACTIVITY, bundle);
            }
            break;
            case "4"://标题新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                bundle.putString("title", bean.getTitle());
                bundle.putString("url", bean.getRedirectURL());
                RouterManager.router(ARouterPathConstant.ADV, bundle);
            }
            break;
            case "5"://视频新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
            }
            break;
            case "8"://互动直播
                break;
            case "101"://抓取新闻
            {
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getID());
                RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
            }
            break;
            default:
                break;

        }
    }

    @OnClick({R2.id.finish_btn, R2.id.news_more, R2.id.live_more, R2.id.info_more, R2.id.course_more})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.finish_btn) {
            finish();
        } else if (id == R.id.news_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_COLUMN_NEWS)
                    .withString("id", mBean.getNewsCatalogId() + "")
                    .withString("title", "校园新闻")
                    .navigation();
        } else if (id == R.id.live_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.TELETEXT_LIST)
                    .withString("title", "校园直播")
                    .withString("type", schoolId + "")
                    .navigation();
        } else if (id == R.id.info_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.NEWS_LIST)
                    .withString("title", "校园资讯")
                    .withString("id", mBean.getInfoCatalogId() + "")
                    .navigation();
        } else if (id == R.id.course_more) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SCHOOL_COLUMN_COURSE)
                    .withInt("schoolId", schoolId)
                    .navigation();
        }
    }
}
